package com.google.googlemarket;

import android.animation.ValueAnimator;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.text.format.Formatter;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.googlemarket.bean.AppDetailInfo;
import com.google.googlemarket.download.DownloadInfo;
import com.google.googlemarket.download.DownloadManager;
import com.google.googlemarket.download.DownloadService;
import com.google.googlemarket.fragement.NetUtils;
import com.google.googlemarket.http.BitmapHelp;
import com.google.googlemarket.http.Urls;
import com.google.googlemarket.utils.ApkUtils;
import com.google.googlemarket.utils.JsonUtil;
import com.google.googlemarket.utils.Keys;
import com.google.googlemarket.utils.Logger;
import com.google.googlemarket.view.Statelayout;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

import java.io.File;
import java.util.HashMap;

/**
 * Created by Administrator on 2017/9/25.
 */
public class AppDetailActivity extends ActionBarActivity{

    private Activity mContext;
    private ScrollView scroll_view;
    private TextView detail_app_name;
    private TextView detail_download_number;
    private TextView detail_version;
    private TextView detail_app_size;
    private TextView detail_online_date;
    private RatingBar detail_ratingbar;
    private ImageView detail_icon;
    private LinearLayout detail_save_icon;
    private LinearLayout detail_save;
    private LinearLayout detail_save_desc;
    private LinearLayout detail_screen;
    private LinearLayout detail_introduction;
    private ImageView detail_introduction_arrow;
    private TextView detail_introduction_desc;
    private ImageView detail_save_arrow;
    private Statelayout statelayout;
    boolean safeIsOpened = false;
    boolean descOpend = false;
    private ProgressBar detail_prograssbar;
    private TextView detail_download;
    private ActionBar actionBar;
    private DownloadManager downloadManager;
    private AppDetailInfo detailInfo;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        statelayout = new Statelayout(mContext);
        statelayout.setContentView(R.layout.activity_detail);
        setContentView(statelayout);

        initView();
        initListener();
        initData();
    }

    private void initView() {
        //第一块内容
        scroll_view = (ScrollView) findViewById(R.id.detail_scroll_view);
        detail_ratingbar = (RatingBar) findViewById(R.id.detail_ratingbar);
        detail_app_name = (TextView) findViewById(R.id.detail_app_name);
        detail_icon = (ImageView) findViewById(R.id.detail_icon);
        detail_download_number = (TextView) findViewById(R.id.detail_download_number);
        detail_version = (TextView) findViewById(R.id.detail_version);
        detail_online_date = (TextView) findViewById(R.id.detail_online_date);
        detail_app_size = (TextView) findViewById(R.id.detail_app_size);


        //第二块内容
        detail_save = (LinearLayout) findViewById(R.id.detail_save);
        detail_save_desc = (LinearLayout) findViewById(R.id.detail_save_desc);
        detail_save_icon = (LinearLayout) findViewById(R.id.detail_save_icon);
        detail_save_arrow = (ImageView) findViewById(R.id.detail_save_arrow);

        for (int i=0;i<4;i++){
            detail_save_icon.getChildAt(i).setVisibility(View.GONE);
            detail_save_icon.getChildAt(i).setVisibility(View.GONE);
        }

        detail_save_desc.getLayoutParams().height=0;
        detail_save_desc.requestLayout();

        //初始化第三块内容
        detail_screen = (LinearLayout) findViewById(R.id.detail_screen);
        for (int i=0;i<detail_screen.getChildCount();i++){
            detail_screen.getChildAt(i).setVisibility(View.GONE);
        }

        //初始化第四块内容
        detail_introduction = (LinearLayout) findViewById(R.id.detail_introduction);
        detail_introduction_arrow = (ImageView) findViewById(R.id.detail_introduction_arrow);
        detail_introduction_desc = (TextView) findViewById(R.id.detail_introduction_desc);

        //初始化下载控件
        detail_prograssbar = (ProgressBar) findViewById(R.id.detail_prograssbar);
        detail_download = (TextView) findViewById(R.id.detail_download);

        initActionBar();
    }

    private void initActionBar() {
        actionBar = getSupportActionBar();
        actionBar.setDefaultDisplayHomeAsUpEnabled(true);
    }

    //设置指示器
    private void initListener() {
        //safe中隐藏的信息展示
        detail_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                safeToggle();
            }
        });
        //introduction中的信息展示
        detail_introduction_desc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                descToggle();
            }
        });
        //下载
        detail_prograssbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onDownLoadClick();
            }
        });

    }

    private void descToggle() {
        int sevenHight = getSevenHight();
        int allHight = getAllHight();

        ValueAnimator valueAnimator = new ValueAnimator();
        if (descOpend){
            valueAnimator = ValueAnimator.ofInt(allHight, sevenHight);
            detail_introduction_arrow.setBackgroundResource(R.drawable.arrow_down);
        }else{
            valueAnimator = ValueAnimator.ofInt(sevenHight, allHight);
            detail_introduction_arrow.setBackgroundResource(R.drawable.arrow_up);
        }

        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                Integer integer = (Integer) valueAnimator.getAnimatedValue();
                detail_introduction_desc.getLayoutParams().height=integer;
                detail_introduction_desc.requestLayout();
            }
        });
        valueAnimator.setDuration(200);
        valueAnimator.start();
        descOpend = !descOpend;
    }

    private int getAllHight() {
        TextView textView = new TextView(mContext);
        textView.setTextSize(14);
        textView.setText(detail_introduction_desc.getText());
        int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(detail_introduction_desc.getWidth(), View.MeasureSpec.EXACTLY);
        textView.measure(widthMeasureSpec,0);
        return textView.getMeasuredHeight();
    }

    /**
     * 获取安全信息中的高度
     * @return
     */
    private int getSevenHight() {
        TextView textView = new TextView(mContext);
        textView.setTextSize(14);
        textView.setText("\n\n\n\n\n\n");
        int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(detail_introduction_desc.getWidth(), View.MeasureSpec.EXACTLY);
        textView.measure(widthMeasureSpec,0);
        return textView.getMeasuredHeight();
    }


    /**
     * 安全信息的收缩与展示
     */
    private void safeToggle() {
        int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int hightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        detail_save_desc.measure(widthMeasureSpec,hightMeasureSpec);
        int hight = detail_save_desc.getMeasuredHeight();
        ValueAnimator valueAnimator = new ValueAnimator();
        if (safeIsOpened){
            //关闭
            valueAnimator = ValueAnimator.ofInt(hight, 0);
            detail_save_arrow.setBackgroundResource(R.drawable.arrow_down);
        }else{
            //打开
            valueAnimator = ValueAnimator.ofInt(0, hight);
            detail_save_arrow.setBackgroundResource(R.drawable.arrow_up);
        }

        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                Integer integer = (Integer) valueAnimator.getAnimatedValue();
                detail_save_desc.getLayoutParams().height=integer;
                detail_save_desc.requestLayout();

            }
        });
        valueAnimator.setDuration(2000);
        valueAnimator.start();
        safeIsOpened = !safeIsOpened;
    }

    private void initData() {
        Logger.i(this,"AppDetailActivity memeda");
        requestAsyncTask(1);
        downloadManager = DownloadService.getDownloadManager(MyApp.getmContext());
    }

    /**
     * 网络请求
     * @param i
     */
    private void requestAsyncTask(final int i) {
        new AsyncTask<Void,Void,Object>(){

            @Override
            protected Object doInBackground(Void... params) {
                return AppDetailActivity.this.doInBackground(i);
            }

            @Override
            protected void onPostExecute(Object result) {
                AppDetailActivity.this.onPostExecute(result);
            }
        }.execute();
    }

    private void onPostExecute(Object result) {
        if (result==null){
            return;
        }
        Logger.i(this,"result:"+result);
        String json = (String) result;
        detailInfo = JsonUtil.json2Bean(json, AppDetailInfo.class);
        if (detailInfo ==null){
            statelayout.showFailView();
        }else{
            statelayout.showContentView();
            showAppInfo(detailInfo);
            showSafe(detailInfo);
            showScreen(detailInfo);
            showDes(detailInfo);
            refreshUI();
        }

    }

    /**
     * 简介
     * @param detailInfo
     */
    private void showDes(AppDetailInfo detailInfo) {
        Logger.i(this,"简介："+detailInfo.des);
        detail_introduction_desc.setText(detailInfo.des);
    }

    /**
     * 屏幕截图
     * @param detailInfo
     */
    private void showScreen(AppDetailInfo detailInfo) {
        if (detailInfo.screen==null&&detailInfo.screen.isEmpty()){
            return;
        }

        for (int i=0;i<detailInfo.screen.size();i++){
            String picUrl = Urls.IMAGE+"?name="+detailInfo.screen.get(i);
            BitmapHelp.getBitmapUtils(mContext).display(detail_screen.getChildAt(i),picUrl);
            detail_screen.getChildAt(i).setVisibility(View.VISIBLE);
        }
    }

    /**
     * 验证信息
     * @param detailInfo
     */
    private void showSafe(AppDetailInfo detailInfo) {
        if (detailInfo.safe==null&&detailInfo.safe.isEmpty())
            return;
        for (int i=0;i<detailInfo.safe.size();i++){
            String picUrl = Urls.IMAGE + "?name="+detailInfo.safe.get(i).safeUrl;
            BitmapHelp.getBitmapUtils(mContext).display(detail_save_icon.getChildAt(i),picUrl);
            ((TextView)detail_save_desc.getChildAt(i)).setText(detailInfo.safe.get(i).safeDes);
            detail_save_icon.getChildAt(i).setVisibility(View.VISIBLE);
            detail_save_desc.getChildAt(i).setVisibility(View.VISIBLE);
        }
    }

    /**
     * 应用信息
     * @param detailInfo
     */
    private void showAppInfo(AppDetailInfo detailInfo) {
        String iconUrl = Urls.IMAGE + "?name="+detailInfo.iconUrl;
        BitmapHelp.getBitmapUtils(mContext).display(detail_icon,iconUrl);
        detail_app_name.setText(detailInfo.name);
        detail_ratingbar.setRating(detailInfo.stars);
        detail_download_number.setText(detailInfo.downloadNum);
        detail_version.setText(detailInfo.version);
        detail_online_date.setText(detailInfo.date);
        detail_app_size.setText(Formatter.formatFileSize(mContext,detailInfo.size));
    }

    public Object doInBackground(int requestType){
        String packageName = getIntent().getStringExtra(Keys.PACKAGE_NAME);
        HashMap<String, String> params = new HashMap<>();
        params.put("packageName",packageName);
        return NetUtils.getJson(Urls.DETAIL,params);
    }


    /**
     * 点击下载
     */
    private void onDownLoadClick() {
        DownloadInfo downloadInfo = downloadManager.getDownloadInfoByAppId(detailInfo.id);
        Logger.i(this,"点击了 downloadInfo:"+downloadInfo);
        if (downloadInfo==null){
            //未下载过
            String target = "/sdcard/GoogleMarket83/"+detailInfo.packageName+".apk";
            String appUrl = Urls.DOWNLOAD+"?name="+detailInfo.downloadUrl;
            Logger.i(this,"点击了 detailInfo.id:"+detailInfo.id+",appUrl:"+appUrl+",detalInfo.name:"+detailInfo.name+",target:"+target+",mDownLoadListener:"+mDownLoadListener);
            try {
                downloadManager.addNewDownload(detailInfo.id,appUrl,detailInfo.name,target,true,false,mDownLoadListener);
            } catch (DbException e) {
                e.printStackTrace();
            }
        }else{
            //如果以前下载过，要么继续下载要么暂停
            HttpHandler.State state = downloadInfo.getState();
            switch (state){
                case WAITING:
                case STARTED:
                case LOADING:
                    try {
                        downloadManager.stopDownload(downloadInfo);
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                    break;
                case CANCELLED:
                case FAILURE:
                    try {
                        downloadManager.resumeDownload(downloadInfo,mDownLoadListener);
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                    break;
                case SUCCESS:
                    Logger.i(this,"执行安装");
                    ApkUtils.install(downloadInfo.getFileSavePath());
            }
        }
    }

    DownLoadListener mDownLoadListener = new DownLoadListener();

    class DownLoadListener extends RequestCallBack<File> {

        @Override
        public void onStart() {
            refreshUI();
        }

        @Override
        public void onCancelled() {
            refreshUI();

        }

        @Override
        public void onLoading(long total, long current, boolean isUploading) {
            refreshUI();

        }

        @Override
        public void onSuccess(ResponseInfo<File> responseInfo) {
            refreshUI();
        }

        @Override
        public void onFailure(HttpException e, String s) {
            refreshUI();
        }
    }

    private void refreshUI() {
        DownloadInfo downloadInfo = downloadManager.getDownloadInfoByAppId(detailInfo.id);
        if (downloadInfo==null){
            //原来没有下载过
            detail_download.setText("下载");
            return;
        }
        HttpHandler.State state = downloadInfo.getState();
        switch (state){
            case WAITING:
                break;
            case STARTED:
            case LOADING:
            case CANCELLED:
                if (downloadInfo.getFileLength()>0){
                    int percent = (int) (downloadInfo.getProgress() * 100 / downloadInfo.getFileLength());
                    detail_prograssbar.setProgress(percent);
                    detail_download.setText(percent+"%");
                }else{
                    detail_prograssbar.setProgress(0);
                    detail_download.setText("0%");
                }
                if (state== HttpHandler.State.CANCELLED){
                    detail_download.setText("暂停");
                }
                break;
            case SUCCESS:
                detail_prograssbar.setProgress(100);
                detail_download.setText("安装");
                break;
            case FAILURE:
                detail_download.setText("重试");
                break;
            default:
                break;
        }

    }
}
